package com.ruoyi.yipaiju.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.CurrencyUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpRequest;
import com.ruoyi.common.utils.http.HttpRespons;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.yipaiju.domain.WXOpenid;
import com.ruoyi.yipaiju.service.IWechatService;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;
import java.util.Base64;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;

@Service
public class WechatServiceImpl implements IWechatService {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ISysConfigService configService;

    @Override
    public WXOpenid getWXOpenid(String code) {
        SortedMap<String, String> map = new TreeMap<>();
        String appid = configService.selectConfigByKey("biz.wechat.xcx.appid");
        map.put("appid", appid);
        map.put("secret", configService.selectConfigByKey("biz.wechat.xcx.secret"));
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");

        String queryString = CurrencyUtil.mapToStr(map);

        try {
            HttpRequest httpRequest = new HttpRequest();
            HttpRespons httpRespons = httpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session?"+queryString);
            ObjectMapper mapper = new ObjectMapper();
            WXOpenid wxOpenid = mapper.readValue(httpRespons.getContent(), WXOpenid.class);
            if (null == wxOpenid) {
                throw new BusinessException("小程序授权失败");
            }
            wxOpenid.setAppid(appid);
            return wxOpenid;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new BusinessException("小程序授权失败");
        }
    }

    @Override
    public JSONObject getUserInfo(String encryptedData, String sessionkey, String iv) {
        // 被加密的数据
        byte[] dataByte = org.codehaus.xfire.util.Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = org.codehaus.xfire.util.Base64.decode(sessionkey);
        // 偏移量
        byte[] ivByte = org.codehaus.xfire.util.Base64.decode(iv);
        try {
            // 如果密钥不足16位，那么就补足. 这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                return JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            throw new BusinessException("数据解析失败");
        }
        throw new BusinessException("数据解析失败");
    }

    @Override
    public String getAccessToken(String appid, String secret) {
        String tokenKey = "access_token:"+appid;
        String accessToken = redisCache.getCacheObject(tokenKey);
        if (StringUtils.isEmpty(accessToken)){
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
            HttpRequest httpRequest = new HttpRequest();
            HttpRespons httpRespons = httpRequest.sendGet(url);
            if (httpRespons != null && StringUtils.isNotEmpty(httpRespons.getContent())){
                JSONObject jsonObject = JSONObject.parseObject(httpRespons.getContent());
                if (jsonObject.containsKey("access_token")){
                    String access_token = jsonObject.getString("access_token");
                    int expires_in = jsonObject.getInteger("expires_in");
                    redisCache.setCacheObject(tokenKey, access_token, expires_in, TimeUnit.SECONDS);
                    return access_token;
                }
            }
        }
        return accessToken;
    }

    @Override
    public String getwxacodeunlimit(String access_token, String page, String scene) throws Exception{
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+access_token;
        HttpRequest httpRequest = new HttpRequest();
        SortedMap<String, String> params = new TreeMap<>();
        params.put("page", page);    // TODO 小程序上线后打开 否则报错
        params.put("scene", scene);
//        params.put("env_version", "trial");
        HttpEntity httpEntity = httpRequest.sendPostStream(url, JSONObject.toJSONString(params));
        if (httpEntity != null) {
//            String content = EntityUtils.toString(httpEntity, "utf-8");
            byte[] bytes = IOUtils.toByteArray(httpEntity.getContent());
            String base64Str = Base64.getEncoder().encodeToString(bytes);
            return base64Str;
        }
        return null;
    }

}
